package com.example.springsecurity04.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * @author yangdc
 * @date 2024/12/3
 */
@RestController
@RequestMapping
public class IndexController {
    @GetMapping
    public ResponseEntity<String> index() {
        return ResponseEntity.ok("Hello");
    }

    @GetMapping("/getUser")
    public ResponseEntity<String> getUser() {
        Object principal = SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        String username = "";
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else if (principal instanceof Principal) {
            username = ((Principal) principal).getName();
        } else {
            username = principal.toString();
        }
        return ResponseEntity.ok("当前登录用户: " + username);
    }
}
